package com.flexrrb.managers
{
	import flash.events.MouseEvent;
	import flash.geom.Point;
	
	import mx.core.UIComponent;
	
	public class MovableManager
	{
		private var _base:UIComponent;
		private var _startPoint:Point; 
		
		public function MovableManager(base:UIComponent=null)
		{
			register(base);
		}
		
		public function register(base:UIComponent):void
		{
			_base = base;
		}
		
		public function unregister():void
		{
			_base = null;	
		}
		
		public function enableMove():void
		{
			_base.addEventListener(MouseEvent.MOUSE_MOVE, onMouseMove, false, 0, true);
			_base.addEventListener(MouseEvent.MOUSE_UP, onMouseUp, false, 0, true);
		}
		
		public function disableMove():void
		{
			_base.removeEventListener(MouseEvent.MOUSE_MOVE, onMouseMove);
			_base.removeEventListener(MouseEvent.MOUSE_UP, onMouseUp);
		}
		
		private function onMouseMove(event:MouseEvent):void
		{
			if(!event.buttonDown)
				return;
			
			var deltaX:Number;
			var deltaY:Number;
			
			if(!_startPoint)
			{
				_startPoint = new Point(_base.stage.mouseX, _base.stage.mouseY);
			}
			
			deltaX = _base.stage.mouseX - _startPoint.x;
			deltaY = _base.stage.mouseY - _startPoint.y;
			
			_base.x += deltaX;
			_base.y += deltaY;
			
			_startPoint.x = _base.stage.mouseX;
			_startPoint.y = _base.stage.mouseY;
		}
		
		private function onMouseUp(event:MouseEvent):void
		{
			_startPoint = null;
		}
	}
}